package cn.niu;

import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

@Service
public class SocketService {

    ServerSocket serverSocket;

    @PostConstruct
    public void init() {
//        initSocket();
    }

    public void initSocket() {
        try {
            serverSocket = new ServerSocket(8889);
            while (true) {
                Socket socket = serverSocket.accept();
                new SocketThread(socket).start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

class SocketThread extends Thread {
    Socket socket;

    public SocketThread(Socket socket) {
        this.socket = socket;
    }

    @Override
    public void run() {
        System.out.println("accepted connection " + socket.getInetAddress() + ":" + socket.getPort());
        try {
            InputStream inputStream = socket.getInputStream();
            FileOutputStream outputStream = new FileOutputStream("D:/test.aac");
            byte[] bytes = new byte[1024];
            int len = 0;
            while ((len = inputStream.read(bytes)) > 0) {
                outputStream.write(bytes, 0, len);
            }

            outputStream.close();
            socket.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
